package com.lds.erp.util;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.alibaba.fastjson.JSON;
import com.lds.erp.base.JsonResult;
import com.lds.erp.enums.ClientSourceEnum;

/**
 * @author hongsir   2017-11-03 20:11
 * @apiNote springboot中使用HttpServletRequest的工具类，获取bean对象，客户端信息等...
 */
public class SpringRequestUtils {

    /**
     * @apiNote 根据传入的类型获取spring管理的对应dao
     * @author hongsir  2017/11/3 20:12:00
     */
    public static <T> T getBean(Class<T> clazz, HttpServletRequest request) {
        BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
        return factory.getBean(clazz);
    }

    /**
     * @apiNote 获取客户端ip地址
     * @author hongsir  2017/11/3 20:01:00
     */
    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.trim() == "" || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.trim() == "" || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.trim() == "" || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 多个路由时，取第一个非unknown的ip
        final String[] arr = ip.split(",");
        for (final String str : arr) {
            if (!"unknown".equalsIgnoreCase(str)) {
                ip = str;
                break;
            }
        }
        return ip;
    }

    public static ClientSourceEnum getClientSource(HttpServletRequest request) {
        String s1 = request.getHeader("user-agent");
        if (s1.contains(ClientSourceEnum.ANDROID.code())) {
            return ClientSourceEnum.ANDROID;
        } else if (s1.contains(ClientSourceEnum.IPHONE.code())) {
            return ClientSourceEnum.IPHONE;
        } else if (s1.contains(ClientSourceEnum.IPAD.code())) {
            return ClientSourceEnum.IPAD;
        } else {
            return ClientSourceEnum.PC;
        }
    }

    /**
     * 直接返回一串json格式的字符串
     * 该方法会自动关闭流,外部无需手动关闭
     *
     * @param response   返回体
     * @param jsonResult 返回信息
     * @throws IOException
     */
    public static void responseJson(HttpServletResponse response, JsonResult jsonResult) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter pw = response.getWriter();
        pw.write(JSON.toJSONString(jsonResult));
        pw.flush();
        pw.close();
    }
}
